import 'package:flutter_bmfutils/BaiduMap/bmfmap_utils.dart';
import 'package:loxen/view/address/city_select_widget.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bmfbase/BaiduMap/map/bmf_models.dart';
import 'package:rxdart/rxdart.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/operation_list_mode.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/view/material/material_order_receive/operation_center_card.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';

class _ViewModel extends BaseViewModel {
  String city;
  String operationId;
  List<Operation> operations;
  BMFCoordinate myCoordinate;

  int currentIndex = 0;
  int childIndex = 0;

  _ViewModel(this.city, this.operationId, this.myCoordinate);

  void changeCity(String city, int currentIndex, int childIndex) {
    if (this.city != city) {
      this.city = city;
      loadData();
    }
  }

  void loadData() {
    if (mState == BaseState.LOADING) return;
    ApiService.operationList(operationId, city: city)
        .doOnListen(() {
          mState = BaseState.LOADING;
          notifyListeners();
        })
        .flatMap((value) => Stream.value(BaseMode<OperationList>(value.data)))
        .flatMap((value) => Stream.value(value?.data))
        .flatMap((value) => Stream.value(value?.results))
        .listen((event) async {
          if (event != null && event.length > 0) {
            operations = event;
            for (var op in operations) {
              double my = await BMFCalculateUtils.getLocationDistance(
                  myCoordinate, BMFCoordinate(double.parse(op.lat), double.parse(op.lng)));
              op.size = my;
            }
            operations.sort((a, b) => a.size.toInt() - b.size.toInt());
            mState = BaseState.CONTENT;
          } else {
            mState = BaseState.EMPTY;
          }
          notifyListeners();
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
          notifyListeners();
          print(stack);
        });
  }
}

class ServiceListWidget extends StatelessWidget {
  final String city;
  final String operationId;
  final BMFCoordinate myCoordinate;

  const ServiceListWidget({Key key, this.city, this.operationId, this.myCoordinate})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_ViewModel>(
      create: (context) {
        var model = _ViewModel(city, operationId, myCoordinate);
        model.loadData();
        return model;
      },
      child: Scaffold(
        backgroundColor: Theme.of(context).backgroundColor,
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 96.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Column(
                children: [
                  Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context,
                          color: Theme.of(context).textTheme.subtitle2.color),
                      Expanded(
                        child: Center(
                          child: Text(
                            StringResources.fu_wu_zhong_xin,
                            style: TextStyle(
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w500,
                                color: Theme.of(context).textTheme.subtitle2.color),
                          ),
                        ),
                      ),
                      MySubassembly.getSearchIcon(null, text: Text('')),
                    ],
                  ),
                  Divider(height: 1.h)
                ],
              ),
            ),
          ),
        ),
        body: Selector<_ViewModel, BaseState>(
            builder: (context, state, _) {
              Widget page;
              switch (state) {
                case BaseState.LOADING:
                  page = LoadingWidget();
                  break;
                case BaseState.EMPTY:
                  page = Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 40.h, bottom: 30.h),
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context)
                                .push(MaterialPageRoute(
                                builder: (_) => CitySelectWidget(
                                  currentCity: context.read<_ViewModel>().city,
                                  currentIndex: context.read<_ViewModel>().currentIndex,
                                  childIndex: context.read<_ViewModel>().childIndex,
                                )))
                                .then((value) {
                              if (value != null) {
                                context.read<_ViewModel>().changeCity(
                                    value['name'], value['currentIndex'], value['childIndex']);
                              }
                            });
                          },
                          child: Row(
                            children: [
                              Image.asset(
                                'images/location_icon.png',
                                width: 36.w,
                                height: 36.w,
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 20.w),
                                child: Builder(
                                  builder: (BuildContext context) {
                                    String text =
                                    context.select<_ViewModel, String>((value) => value.city);
                                    return Text(
                                      text,
                                      style: TextStyle(
                                        fontSize: 28.sp,
                                        color: Colours.main_text,
                                      ),
                                    );
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: EmptyWidget(
                          title: '当前区域暂无服务中心',
                          content: '请切换其他城市查看服务中心',
                        ),
                      ),
                    ],
                  );
                  break;
                case BaseState.FAIL:
                  // TODO: Handle this case.
                  page = FailWidget(
                    onClick: () {
                      context.read<_ViewModel>().loadData();
                    },
                    button: '重试',
                  );
                  break;
                case BaseState.CONTENT:
                  page = Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 40.h, bottom: 30.h),
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context)
                                .push(MaterialPageRoute(
                                    builder: (_) => CitySelectWidget(
                                          currentCity: context.read<_ViewModel>().city,
                                          currentIndex: context.read<_ViewModel>().currentIndex,
                                          childIndex: context.read<_ViewModel>().childIndex,
                                        )))
                                .then((value) {
                              if (value != null) {
                                context.read<_ViewModel>().changeCity(
                                    value['name'], value['currentIndex'], value['childIndex']);
                              }
                            });
                          },
                          child: Row(
                            children: [
                              Image.asset(
                                'images/location_icon.png',
                                width: 36.w,
                                height: 36.w,
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 20.w),
                                child: Builder(
                                  builder: (BuildContext context) {
                                    String text =
                                        context.select<_ViewModel, String>((value) => value.city);
                                    return Text(
                                      text,
                                      style: TextStyle(
                                        fontSize: 28.sp,
                                        color: Colours.main_text,
                                      ),
                                    );
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: SingleChildScrollView(
                          child: Padding(
                            padding: EdgeInsets.only(left: 30.w, right: 30.w),
                            child: Builder(
                              builder: (BuildContext context) {
                                var list = context.watch<_ViewModel>().operations;
                                return ListView.builder(
                                  physics: NeverScrollableScrollPhysics(),
                                  shrinkWrap: true,
                                  itemCount: list.length,
                                  itemBuilder: (context, index) {
                                    var operation = list[index];
                                    return OperationCenterCard(
                                      onSelect: (){
                                        Navigator.pop(context,operation);
                                      },
                                      showGoTo: false,
                                      bean: ItemBean(
                                        operation.size < 1000
                                            ? '${operation.size.toInt()}m'
                                            : '${operation.size.toInt() / 1000}km',
                                        operation.name,
                                        operation.area.province,
                                        operation.area.city,
                                        operation.area.district,
                                        operation.address,
                                        operation.mobile,
                                      ),
                                    );
                                  },
                                );
                              },
                            ),
                          ),
                        ),
                      )
                    ],
                  );
                  break;
              }
              return page;
            },
            selector: (_, value) => value.mState),
      ),
    );
  }
}
